import { createI18n } from 'vue-i18n';
import messages from './locale/index';

let i18nConfig = {
  locale: uni.getLocale(),// 获取已设置的语言
  messages
}
const i18n  = createI18n(i18nConfig);
const t = i18n.global.t;


export class Ble {
	constructor() {
		this.ble = {
			id: "",
			name: "",
		};
	}

	readcommod(mac, uuid1, uuid2, callback) {
		//主动读取设备数据

		uni.readBLECharacteristicValue({
			// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
			deviceId: mac,
			// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
			serviceId: uuid1,
			// 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
			characteristicId: uuid2,
			success(res) {
				//
			},
			fail(res) {},
		});
	}

	//链接
	connectToDevice(id, name) {
		if (this.ble.id) {
			console.log("已经连接上了, 再次断开");
			this.disconnectBluetooth();
		}
		uni.showLoading({
			mask: true,
		});

		this.ble.id = id;
		this.ble.name = name;

		uni.createBLEConnection({
			deviceId: this.ble.id,
			success: (res) => {
				console.log("蓝牙连接中", this.ble.id, this.ble.name);
				uni.$emit("blechenggong", this.ble.id, this.ble.name);

				uni.onBLEConnectionStateChange((res) => {
					if (!res.connected) {
						uni.showToast({
							title: t('bluetooth.disconnected'),
							icon: "none",
							duration: 1000,
						});
						uni.$emit("chenggong", "", "");
						// 蓝牙突然断开
						console.log('蓝牙突然断开')
					}
				});
				setTimeout(() => {
					this.getServices();
				}, 1500);
				uni.stopBluetoothDevicesDiscovery();
			},
			fail: (error) => {
				uni.showToast({
					title: t('bluetooth.connectFail'),
					icon: "none",
				});
			},
			complete() {
				//uni.hideLoading()
			},
		});
	}
	// 获取服务
	getServices() {
		let that = this;

		uni.getBLEDeviceServices({
			deviceId: that.ble.id,
			success(res) {
				// console.log(JSON.stringify(res), ": getBLEDeviceServices");
				const servicesList = res?.services ?? [],
					serviceUUID = (servicesList[1] || servicesList[0]).uuid;
				that.setServices(serviceUUID);
			},
			fail(err) {
				console.error(err);
			},
		});
	}
	// 写入服务
	setServices(serviceUUID) {
		let that = this;
		// console.log("setServices serviceUUID=", serviceUUID);
		uni.getBLEDeviceCharacteristics({
			deviceId: that.ble.id,
			// serviceId: '00001910-0000-1000-8000-00805F9B34FB',
			// serviceId: '1910',
			serviceId: serviceUUID,
			success: (res) => {
				//console.log('getBLEDeviceCharacteristics suceess', JSON.stringify(res))
				const characteristicsList = res.characteristics || [],
					characteristicUUID = (
						characteristicsList[1] || characteristicsList[0]
					).uuid;
				that.startNotifications(serviceUUID, characteristicUUID);
			},
			fail: (error) => {
				console.error("setServices Error", error);
				that.disconnectBluetooth();
			},
		});
	}
	// 接受通知
	startNotifications(serviceIdUUID, characteristicUUID) {
		let that = this;
		let serviceId = "00001910-0000-1000-8000-00805F9B34FB";
		let characteristicId = "00002B10-0000-1000-8000-00805F9B34FB";

		console.log(
			`serviceIdUUID: `,
			serviceId,
			"characteristicUUID:",
			characteristicId
		);

		uni.hideLoading();
		uni.notifyBLECharacteristicValueChange({
			deviceId: this.ble.id,
			serviceId: serviceId,
			characteristicId: characteristicId,
			state: true,
			success: (res) => {
				let sysType = plus.os.name == "iOS" ? "app_ios" : "app_and";
				console.log("sysType=", sysType);
				if (sysType == "app_and") {
					setTimeout(() => {
						that.setMTU(that.ble.id, 500, (result) => {
							if (result.status) {
								that.listenrecv();
								//that.sendCommand(that.ble.id, "55aabbcc")
								setTimeout(() => {
									that.readcommod(that.ble.id, serviceId,
										characteristicId);
								}, 500);
							} else {
								console.error("MTU 设置失败");
								isconnect.value = 0;
								if (type.value.brand == "apple") {
									that.listenrecv();
									that.readcommod(that.ble.id, serviceId,
										characteristicId);
								}
							}
						});
					}, 500);
				} else {
					that.listenrecv();
					//that.sendCommand(that.ble.id, "55aabbcc")
					setTimeout(() => {
						that.readcommod(that.ble.id, serviceId, characteristicId);
					}, 500);
				}

				// todo
			},
			fail: (error) => {
				console.error("通知开启失败", error);
			},
		});
	}

	setMTU(deviceId, mtu, callback) {
		uni.setBLEMTU({
			deviceId: deviceId, // 设备 ID
			mtu: mtu, // 要设置的 MTU 值
			success: (res) => {
				callback &&
					callback({
						status: true,
					});
			},
			fail: (err) => {
				callback &&
					callback({
						status: false,
					});
			},
		});
	}

	gethex(buffer) {
		var hexArr = Array.prototype.map.call(
			new Uint8Array(buffer),
			function(bit) {
				return ("00" + bit.toString(16)).slice(-2);
			}
		);
		return hexArr.join("");
	}
	decode(str) {
		let res = "";
		for (let i = 0; i < str.length; i += 2) {
			let hex = str.substring(i, i + 2);
			res += String.fromCharCode(parseInt(hex, 16));
		}

		return JSON.parse(res);
	}
	listenrecv() {
		console.log("等待蓝牙返回信息");

		uni.onBLECharacteristicValueChange((res) => {
			const value = this.gethex(res.value);
			console.log("value=", value);
			if (value.length == 12) {
				this.ble.devicemac = value;
				uni.$emit("addimei", value);
			} else {
				uni.showToast({
					title: t('bluetooth.dataError'),
					icon: "none",
					duration: 2000,
				});
			}
			let str = this.decode(value);

			if (str.cmd == "configret") {
				uni.$emit("configret", str);
			}
		});
	}

	// 断开设备
	disconnectBluetooth() {
		if (this.ble.id) {
			console.log('蓝牙主动断开')
			uni.closeBLEConnection({
				deviceId: this.ble.id,
				success: () => {},
				fail: (error) => {
					console.error("断开蓝牙设备失败", error);
				},
				complete() {
					this.ble = {};
				},
			});
		} else {
			uni.showToast({
				title: t('bluetooth.notConnected'),
				icon: "none",
			});
		}
	}
	// 蓝牙发送指令
	sendCommand(mac, command) {
		uni.showLoading({
			title: t('bluetooth.sendingData'),
			mask: true,
		});
		const buffer = new ArrayBuffer(command.length);
		const dataView = new DataView(buffer);
		for (let i = 0; i < command.length; i++) {
			dataView.setUint8(i, command.charCodeAt(i));
		}
		// 发送数据

		uni.writeBLECharacteristicValue({
			deviceId: mac,
			serviceId: "00001910-0000-1000-8000-00805F9B34FB",
			characteristicId: "00002B11-0000-1000-8000-00805F9B34FB",
			value: buffer,
			writeNoResponse: 'writeNoResponse',
			success: (res) => {
				console.log("writeBLECharacteristicValue success");

				uni.showToast({
					title: t('bluetooth.success'),
					icon: "none",
				});
			},
			fail: (error) => {
				console.error("writeBLECharacteristicValue error", error);
				uni.showToast({
					title: t('bluetooth.writeError'),
					icon: "none",
				});
			},
			complete() {
				console.log("writeBLECharacteristicValue complete");
				uni.hideLoading();
			},
		});
	}
}